// 2024/5/22: 首个版本
// 2024/6/25: 支持API3
// 2025/7/30: 新增启用写入加密文件选项。改良密码设置界面布局

using System;
using System.Threading.Tasks;
using ASEva;
using ASEva.UIEto;
using ASEva.Utility;
using Eto.Forms;
using Eto.Drawing;

namespace CommonSource
{
    class DataEncryptionConfigDialog : DialogPanel
    {
        public DataEncryptionConfigDialog(WorkflowEncryptionCallback callback, Icon icon = null)
        {
            Assert.HostSide();

            Icon = icon;
            Title = chinese ? "数据加密配置" : "Data encryption config";
            this.SetFixMode(420, 285, true);

            var mainLayout = this.SetContentAsColumnLayout();
            var groupOptions = mainLayout.AddGroupBox(chinese ? "选项" : "Options", false, 0, 80);
            var groupPassword = mainLayout.AddGroupBox(chinese ? "设置密码" : "Password settings", true);

            var optionsLayout = groupOptions.SetContentAsColumnLayout();
            var checkRecordEncryption = optionsLayout.AddCheckBox(chinese ? "启用写入加密文件" : "Enable encrypted file writers", false, AgencyAsync.GetGlobalParameter("System.RecordEncryption", "no").Result == "yes");
            optionsLayout.AddLabel(chinese ? "(写入的数据文件可能无法被第三方软件打开)" : "(Written data files may not be opened by 3rd-party software)").TextColor = Colors.DarkOrange;

            var passwordLayout = groupPassword.SetContentAsColumnLayout();
            var tableLayout = passwordLayout.AddTableLayout(true);
            var row = tableLayout.AddRow(true);
            row.AddLabel(chinese ? "旧密码:" : "Old password:");
            var textOld = row.AddControl(new PasswordBox{ Enabled = false, PasswordChar = '●' }, true);
            var buttonUnlock = row.AddButton(chinese ? "解锁" : "Unlock", false, false, 80);
            row = tableLayout.AddRow(true);
            row.AddLabel(chinese ? "新密码:" : "New password:");
            var textNew = row.AddControl(new PasswordBox{ Enabled = false, PasswordChar = '●' }, true);
            row = tableLayout.AddRow(true);
            row.AddLabel(chinese ? "确认密码:" : "Confirm password:");
            var textConfirm = row.AddControl(new PasswordBox{ Enabled = false, PasswordChar = '●' }, true);
            var buttonUpdate = row.AddButton(chinese ? "更新" : "Update", false, false, 80);
            buttonUnlock.Enabled = buttonUpdate.Enabled = false;
            passwordLayout.AddLabel(chinese ? "(使用空密码也可写入加密文件)" : "(Encrypted files can also be written with empty password)");

            var defaultPassword = callback.UnlockDataKey(null);
            if (defaultPassword)
            {
                buttonUnlock.Text = chinese ? "已解锁" : "Unlocked";
                textNew.Enabled = textConfirm.Enabled = true;
                textNew.Focus();
            }
            else
            {
                textOld.Enabled = true;
                textOld.Focus();
            }

            checkRecordEncryption.CheckedChanged += delegate
            {
                AgencyAsync.SetGlobalParameter("System.RecordEncryption", checkRecordEncryption.Checked.Value ? "yes" : "no");
            };

            textOld.TextChanged += delegate
            {
                buttonUnlock.Enabled = textOld.Text.Length > 0;
            };

            textOld.KeyUp += async (o, e) =>
            {
                if (e.Key == Keys.Enter)
                {
                    await Task.Delay(10);
                    if (buttonUnlock.Enabled) buttonUnlock.PerformClick();
                }
            };

            buttonUnlock.Click += delegate
            {
                if (callback.UnlockDataKey(textOld.Text))
                {
                    buttonUnlock.Text = chinese ? "已解锁" : "Unlocked";
                    buttonUnlock.Enabled = textOld.Enabled = false;
                    textNew.Enabled = textConfirm.Enabled = buttonUpdate.Enabled = true;
                    textNew.Focus();
                }
                else
                {
                    App.ShowMessageBox(chinese ? "密码错误。" : "Wrong password.");
                }
            };

            textNew.TextChanged += delegate
            {
                var confirmed = textConfirm.Text == textNew.Text;
                if (!defaultPassword) buttonUpdate.Enabled = confirmed;
                else buttonUpdate.Enabled = confirmed && textNew.Text.Length > 0;
            };
            
            textConfirm.TextChanged += delegate
            {
                var confirmed = textConfirm.Text == textNew.Text;
                if (!defaultPassword) buttonUpdate.Enabled = confirmed;
                else buttonUpdate.Enabled = confirmed && textNew.Text.Length > 0;
            };
            
            textNew.KeyUp += async (o, e) =>
            {
                if (e.Key == Keys.Enter)
                {
                    await Task.Delay(10);
                    if (buttonUpdate.Enabled) buttonUpdate.PerformClick();
                }
            };

            textConfirm.KeyUp += async (o, e) =>
            {
                if (e.Key == Keys.Enter)
                {
                    await Task.Delay(10);
                    if (buttonUpdate.Enabled) buttonUpdate.PerformClick();
                }
            };

            buttonUpdate.Click += async delegate
            {
                callback.UpdateDataKey(textNew.Text.Length == 0 ? null : textNew.Text);
                await App.ShowMessageBox(chinese ? "密码已更新。" : "Password updated.");
                Close();
            };
        }

        private bool chinese = AgencyLocal.GetAppLanguage() == Language.Chinese;
    }
}